import pyautogui
import time
import ast

board_origin = (767, 254)
cell_size = (42, 42)

def get_screen_position(cell):
    return (board_origin[0] + cell[1] * cell_size[0],
            board_origin[1] + cell[0] * cell_size[1])

def execute_instruction(instruction, click_delay):
    if instruction[0] == 'eliminate':
        for cell in instruction[1]:
            screen_position = get_screen_position(cell)
            print(f"click {cell}") 
            pyautogui.click(screen_position)
            time.sleep(click_delay)
    elif instruction[0] == 'global_elimination':
        for cell in instruction[1]:
            screen_position = get_screen_position(cell)
            print(f"click {cell}") 
            pyautogui.click(screen_position)
            time.sleep(click_delay)

    else:
        _, cell, direction, steps = instruction
        start_position = get_screen_position(cell)
        # print(f"start {cell}") 

        if direction == 'up':
            end_position = (
                start_position[0], start_position[1] - steps * cell_size[1])
        elif direction == 'down':
            end_position = (
                start_position[0], start_position[1] + steps * cell_size[1])
        elif direction == 'left':
            end_position = (
                start_position[0] - steps * cell_size[0], start_position[1])
        elif direction == 'right':
            end_position = (
                start_position[0] + steps * cell_size[0], start_position[1])
        end_cell = (cell[0] + (end_position[1] - start_position[1]) // cell_size[1],
                    cell[1] + (end_position[0] - start_position[0]) // cell_size[0])
        # print(f"===>>end {end_cell}") 
        print(f"start {cell} ===>> end {end_cell}")

        pyautogui.moveTo(start_position)
        pyautogui.mouseDown()
        pyautogui.moveTo(end_position, duration=0.3)
        time.sleep(0.1)  # 在松开鼠标左键之前等待0.2秒
        pyautogui.mouseUp()  

        time.sleep(click_delay)


def read_instructions(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        instructions = []
        for line in lines:
            instruction = ast.literal_eval(line.strip())
            if instruction[0] in ['eliminate', 'global_elimination']:
                instructions.append(instruction)
            else:
                action, cell, direction, steps = instruction
                instructions.append((str(action), cell, direction, steps))
        return instructions

instructions = read_instructions('move_path.txt')

click_delay = 0.2  # 可以根据需要调整这个值

for instruction in instructions:
    execute_instruction(instruction, click_delay)
